package logger

import (
	"io"
	"log"
	"net"
	"net/http"
)

var logger *log.Logger

// func accessLog(ip, method, url, userAgent string, status int) {
// 	// logFile, _ := os.Open("log/access.log")
// 	logger := log.New(os.Stdout, "", log.Ldate|log.Ltime)
// 	logger.Printf("%s %s %s %s %d", ip, method, url, userAgent, status)
// 	// log.SetOutput(logFile)
// 	// log.Printf("%s,%s", log.Ldate|log.LstdFlags, log.Ltime)
// 	// defer logFile.Close()
// }

func InitLogger(writer io.Writer) {
	logger = log.New(writer, "", 0)
}

// 记录日志，重写HandlerFunc，使用闭包，增加功能--装饰器

func LoggerWrapper(action http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// 验证信息加载action之前
		action(w, r)
		if logger != nil {
			ip, _, _ := net.SplitHostPort(r.RemoteAddr)
			logger.Printf(`%s %s "%s" %s`, ip, r.Method, r.URL.Path, r.Header.Get("user-agent"))
		}

	}

}
